package com.rong.shop.service.impl;

import com.rong.shop.mapper.AddressDistrictMapper;
import com.rong.shop.mapper.CartMapper;
import com.rong.shop.mapper.ProductMapper;
import com.rong.shop.pojo.AddressDistrict;
import com.rong.shop.pojo.Cart;
import com.rong.shop.pojo.vo.CartVO;
import com.rong.shop.service.IAddressDistrictService;
import com.rong.shop.service.ICartService;
import com.rong.shop.service.ex.AccessDeniedException;
import com.rong.shop.service.ex.InsertException;
import com.rong.shop.service.ex.NotFoundCartException;
import com.rong.shop.service.ex.UpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    private Date date = new Date();

    /**
     * 查询用户下的购物车记录
     * @param uid   前端传来的uid
     * @return  List<Cart>
     */
    @Override
    public List<CartVO> findByUid(Integer uid) {
        return cartMapper.findByUid(uid);
    }

    /**
     * 根据多个cids参数，来查询记录
     * @param cids  前端传来的cids数组
     * @param uid   session中获取到的uid，来辨别是否是本用户在操作
     * @return List<CartVO> 返回选中的记录
     */
    @Override
    public List<CartVO> findByCids(Integer[] cids, Integer uid) {

        List<CartVO> cartVOs = cartMapper.findByCids(cids);
        Iterator<CartVO> iterator = cartVOs.iterator();
        try{
            while (iterator.hasNext()) {
                CartVO c = iterator.next();
                if (!c.getUid().equals(uid)){
                    // 如果该记录不是当前用户的,将其在 列表 中删除
                    cartVOs.remove(c);
                }
            }
        }catch (ConcurrentModificationException e){
            throw new NotFoundCartException("没有找到该记录：" + e.getMessage());
        }
        return cartVOs;
    }

    /**
     * 添加购物车
     * @param uid       session中获取到的pid
     * @param pid       前端传来的pid
     * @param amount    前端传来的amout, 表示数量
     * @param username  session中获取到的username
     */
    @Override
    public void addCart(Integer uid, Integer pid, Integer amount, String username) {

        //1, 首先先查询购物车里：是否有该商品的记录
        Cart result = cartMapper.findByUidAndPid(uid, pid);
        if(result == null){
            // 等于空说明表里没有查找到该记录；进行insert操作
            // 2.进行insert操作
            Cart cart = new Cart();
            cart.setUid(uid);
            cart.setPid(pid);
            cart.setNum(amount);
            //为了获取价格 需要用到**联表查询**
            cart.setPrice(productMapper.findById(pid).getPrice());

            cart.setModifiedUser(username);
            cart.setModifiedTime(date);
            cart.setCreatedTime(date);
            cart.setCreatedUser(username);

            Integer addRows = cartMapper.insert(cart);
            if(addRows < 1){
                throw new InsertException("新增购物车数据异常");
            }
        }else {
            // 3.更新操作
            //    从已有的数据中获取数量，再添加上传递过来的数量，进行更新
            Integer num = result.getNum() + amount;
            Integer updateRows = cartMapper.updateNumByCid(result.getCid(), num, username, date);
            if(updateRows < 1){
                throw new UpdateException("更新购物车数据异常");
            }

        }

    }

    /**
     * 根据前端获取到的cid 来更新购物车订单里的商品数量； 返回更新的num
     * @param cid           前端按钮传来的cid
     * @param uid           session中获取到的uid
     * @param username      session中获取到的username
     * @return num          num记录数
     */
    @Override
    public Integer addNum(Integer cid, Integer uid, String username) {
        Cart result = cartMapper.findByCid(cid);
        if(result == null){
            throw new NotFoundCartException("没有找到购物车的 "+ cid +" 记录");
        }

        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问！");
        }

        Integer num = result.getNum() + 1;
        Integer rows = cartMapper.updateNumByCid(cid,num, username, new Date());
        if(rows < 1){
            throw new UpdateException("数量+ 更新异常");
        }
        return num;
    }

    @Override
    public Integer reduceNum(Integer cid, Integer uid, String username) {
        Cart result = cartMapper.findByCid(cid);
        if(result == null){
            throw new NotFoundCartException("没有找到购物车的 "+ cid +" 记录");
        }

        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问！");
        }

        Integer num = result.getNum() - 1;
        if(num < 1){
            num = 0;
        }

        Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date());
        if(rows < 1){
            throw new UpdateException("数量- 更新异常");
        }
        return num;
    }


}
